const mysql = require('mysql2/promise');
require('dotenv').config({ path: './nestjs-app/.env' });

/**
 * 测试娱乐城定时任务时间设置
 * 检查大小和赤壁期数的时间是否正确
 */

class CasinoTimingTester {
  constructor() {
    this.connection = null;
  }

  async connect() {
    try {
      this.connection = await mysql.createConnection({
        host: process.env.DB_HOST || '43.143.253.188',
        port: process.env.DB_PORT || 3306,
        user: process.env.DB_USER || 'nextjs',
        password: process.env.DB_PASS || 'yEAiRE2jcxTyRBy5',
        database: process.env.DB_NAME || 'nextjs',
        timezone: '+08:00'
      });
      console.log('✅ 数据库连接成功');
    } catch (error) {
      console.error('❌ 数据库连接失败:', error.message);
      throw error;
    }
  }

  async disconnect() {
    if (this.connection) {
      await this.connection.end();
      console.log('🔌 数据库连接已关闭');
    }
  }

  async checkTableStructure() {
    try {
      console.log('\n🔍 检查表结构...');
      
      // 检查大小期数表结构
      const [diceColumns] = await this.connection.execute(`
        SHOW COLUMNS FROM casino_dice_rounds
      `);
      
      console.log('📊 大小期数表结构:');
      diceColumns.forEach(col => {
        console.log(`  - ${col.Field}: ${col.Type} ${col.Null === 'YES' ? '(可空)' : '(非空)'}`);
      });
      
      // 检查赤壁期数表结构
      const [chibiColumns] = await this.connection.execute(`
        SHOW COLUMNS FROM casino_chibi_rounds
      `);
      
      console.log('\n📊 赤壁期数表结构:');
      chibiColumns.forEach(col => {
        console.log(`  - ${col.Field}: ${col.Type} ${col.Null === 'YES' ? '(可空)' : '(非空)'}`);
      });
      
    } catch (error) {
      console.error('❌ 检查表结构失败:', error.message);
    }
  }

  async checkDiceRounds() {
    try {
      console.log('\n🎲 检查大小玩法期数时间设置...');
      
      // 查询当前期数
      const [currentRounds] = await this.connection.execute(`
        SELECT id, start_time, end_time, status, 
               TIMESTAMPDIFF(SECOND, NOW(), end_time) as remainingSeconds,
               TIMESTAMPDIFF(SECOND, start_time, end_time) as durationSeconds
        FROM casino_dice_rounds 
        WHERE status = 0 
        ORDER BY id DESC 
        LIMIT 5
      `);

      if (currentRounds.length === 0) {
        console.log('📭 没有找到下注中的大小期数');
        return;
      }

      console.log(`📊 找到 ${currentRounds.length} 个大小期数:`);
      currentRounds.forEach((round, index) => {
        console.log(`\n期数 ${index + 1}:`);
        console.log(`  - ID: ${round.id}`);
        console.log(`  - 开始时间: ${round.startTime}`);
        console.log(`  - 结束时间: ${round.endTime}`);
        console.log(`  - 状态: ${round.status} (0=下注中, 1=开奖中, 2=已结束)`);
        console.log(`  - 剩余秒数: ${round.remainingSeconds}`);
        console.log(`  - 期数时长: ${round.durationSeconds}秒`);
        
        if (round.remainingSeconds > 600) {
          console.log(`  ⚠️  警告：剩余时间超过10分钟！`);
        } else if (round.remainingSeconds < 0) {
          console.log(`  ⚠️  警告：期数已过期！`);
        } else {
          console.log(`  ✅ 时间设置正常`);
        }
      });

    } catch (error) {
      console.error('❌ 检查大小期数失败:', error.message);
    }
  }

  async checkChibiRounds() {
    try {
      console.log('\n🏰 检查赤壁玩法期数时间设置...');
      
      // 查询当前期数
      const [currentRounds] = await this.connection.execute(`
        SELECT id, startTime, endTime, status, 
               TIMESTAMPDIFF(SECOND, NOW(), endTime) as remainingSeconds,
               TIMESTAMPDIFF(SECOND, startTime, endTime) as durationSeconds
        FROM casino_chibi_rounds 
        WHERE status = 0 
        ORDER BY id DESC 
        LIMIT 5
      `);

      if (currentRounds.length === 0) {
        console.log('📭 没有找到下注中的赤壁期数');
        return;
      }

      console.log(`📊 找到 ${currentRounds.length} 个赤壁期数:`);
      currentRounds.forEach((round, index) => {
        console.log(`\n期数 ${index + 1}:`);
        console.log(`  - ID: ${round.id}`);
        console.log(`  - 开始时间: ${round.startTime}`);
        console.log(`  - 结束时间: ${round.endTime}`);
        console.log(`  - 状态: ${round.status} (0=下注中, 1=开奖中, 2=已结束)`);
        console.log(`  - 剩余秒数: ${round.remainingSeconds}`);
        console.log(`  - 期数时长: ${round.durationSeconds}秒`);
        
        if (round.remainingSeconds > 600) {
          console.log(`  ⚠️  警告：剩余时间超过10分钟！`);
        } else if (round.remainingSeconds < 0) {
          console.log(`  ⚠️  警告：期数已过期！`);
        } else {
          console.log(`  ✅ 时间设置正常`);
        }
      });

    } catch (error) {
      console.error('❌ 检查赤壁期数失败:', error.message);
    }
  }

  async checkRecentRounds() {
    try {
      console.log('\n📈 检查最近期数历史...');
      
      // 查询最近的大小期数
      const [diceRounds] = await this.connection.execute(`
        SELECT id, startTime, endTime, status, 
               TIMESTAMPDIFF(SECOND, startTime, endTime) as durationSeconds,
               created_at
        FROM casino_dice_rounds 
        ORDER BY id DESC 
        LIMIT 10
      `);

      console.log(`📊 最近 ${diceRounds.length} 个大小期数:`);
      diceRounds.forEach((round, index) => {
        console.log(`\n期数 ${index + 1}:`);
        console.log(`  - ID: ${round.id}`);
        console.log(`  - 开始时间: ${round.startTime}`);
        console.log(`  - 结束时间: ${round.endTime}`);
        console.log(`  - 状态: ${round.status}`);
        console.log(`  - 期数时长: ${round.durationSeconds}秒`);
        console.log(`  - 创建时间: ${round.created_at}`);
      });

      // 查询最近的赤壁期数
      const [chibiRounds] = await this.connection.execute(`
        SELECT id, startTime, endTime, status, 
               TIMESTAMPDIFF(SECOND, startTime, endTime) as durationSeconds,
               created_at
        FROM casino_chibi_rounds 
        ORDER BY id DESC 
        LIMIT 10
      `);

      console.log(`\n📊 最近 ${chibiRounds.length} 个赤壁期数:`);
      chibiRounds.forEach((round, index) => {
        console.log(`\n期数 ${index + 1}:`);
        console.log(`  - ID: ${round.id}`);
        console.log(`  - 开始时间: ${round.startTime}`);
        console.log(`  - 结束时间: ${round.endTime}`);
        console.log(`  - 状态: ${round.status}`);
        console.log(`  - 期数时长: ${round.durationSeconds}秒`);
        console.log(`  - 创建时间: ${round.created_at}`);
      });

    } catch (error) {
      console.error('❌ 检查最近期数失败:', error.message);
    }
  }

  async fixTimingIssues() {
    try {
      console.log('\n🔧 尝试修复时间设置问题...');
      
      const now = new Date();
      const newEndTime = new Date(now.getTime() + 10 * 60 * 1000); // 当前时间 + 10分钟
      
      // 修复大小期数时间
      const [diceResult] = await this.connection.execute(`
        UPDATE casino_dice_rounds 
        SET startTime = ?, endTime = ?
        WHERE status = 0 AND TIMESTAMPDIFF(SECOND, NOW(), endTime) > 600
      `, [now, newEndTime]);
      
      if (diceResult.affectedRows > 0) {
        console.log(`✅ 修复了 ${diceResult.affectedRows} 个大小期数的时间设置`);
      } else {
        console.log('ℹ️ 没有需要修复的大小期数');
      }
      
      // 修复赤壁期数时间
      const [chibiResult] = await this.connection.execute(`
        UPDATE casino_chibi_rounds 
        SET startTime = ?, endTime = ?
        WHERE status = 0 AND TIMESTAMPDIFF(SECOND, NOW(), endTime) > 600
      `, [now, newEndTime]);
      
      if (chibiResult.affectedRows > 0) {
        console.log(`✅ 修复了 ${chibiResult.affectedRows} 个赤壁期数的时间设置`);
      } else {
        console.log('ℹ️ 没有需要修复的赤壁期数');
      }
      
    } catch (error) {
      console.error('❌ 修复时间设置失败:', error.message);
    }
  }

  async runTests() {
    try {
      await this.connect();
      
      console.log('🧪 开始检查娱乐城定时任务时间设置...');
      
      // 1. 检查当前期数时间
      await this.checkDiceRounds();
      await this.checkChibiRounds();
      
      // 2. 检查最近期数历史
      await this.checkRecentRounds();
      
      // 3. 尝试修复时间问题
      await this.fixTimingIssues();
      
      // 4. 再次检查修复后的情况
      console.log('\n🔄 修复后再次检查...');
      await this.checkDiceRounds();
      await this.checkChibiRounds();
      
      console.log('\n🎉 检查完成');
      
    } catch (error) {
      console.error('❌ 测试执行失败:', error.message);
    } finally {
      await this.disconnect();
    }
  }
}

// 执行测试
if (require.main === module) {
  const tester = new CasinoTimingTester();
  tester.runTests()
    .then(() => {
      console.log('\n✅ 娱乐城定时任务时间检查完成');
      process.exit(0);
    })
    .catch((error) => {
      console.error('\n❌ 娱乐城定时任务时间检查失败:', error.message);
      process.exit(1);
    });
}

module.exports = { CasinoTimingTester };
